<?php

/**
 * 账户管理
 * @author renpper
 * @date 2015-1-5
 */
 
namespace Admin\Controller;
class ManagerController extends BaseController {
	
	private $manager_model, $roles, $status;
	
	public function _initialize(){
		$this->manager_model = getInstance('Admin\Model\ManagerModel');
		$this->roles = $this->getRoles();
		$this->status = array('U'=>'可用', 'D'=>'锁定');
	}
	
	
	/**
	 * 获取角色
	 */
	protected function getRoles(){
		if($roles = getInstance('Admin\Model\RoleModel')->field('id,name')->select()){
			foreach($roles as $r){
				$data[$r['id']] = $r['name'];
			}
		}
		return $data;
	}
	
	
	/**
	 * 列表页
	 */
	public function index(){
		$page = $this->view->page(count($this->manager_model->where('form')->select()),'uid');
		$users = $this->manager_model->where('form')->order($page['orderFieldStr'])->limit($page['limit'].','.$page['numPerPage'])->select();
		if(is_array($users)){ 
			foreach($users as &$user){
				$user['role_id'] = $this->roles[$user['role_id']];
				$user['state'] = $this->status[$user['state']];
			}
		}
		$this->assign('roles', $this->roles);	
		$this->assign('users', $users);
		$this->assign('page', $page);
		$this->display('Admin/View/Manager/index.php');
	}
	
	/**
	 * 验证表单提交的值是否符合条件
	 */
	private function checkValidate($flag='add'){
		$sql = "username='{$_POST['username']}'";
		$sql .= ($flag == 'update') ? " AND uid!={$_POST['uid']}" : '';
		$password = $_POST['password'];
		$pwd_len = strlen($password);
		if(count($this->manager_model->where($sql)->select()) > 0){
			$this->ajaxReturn(300, '用户名已经存在');
		}else if($pwd_len<6 || $pwd_len >8){
			$this->ajaxReturn(300, '密码长度必须限制在6~8位之间');
		}
		$_POST['password'] = md5($password);
	}
	
	
	/**
	 * 添加用户
	 */
	public function add(){
		if(count($_POST) > 0){
			$this->checkValidate();
			$_POST['register_time'] = date('Y-m-d H:i:s');
			if($this->manager_model->add($_POST)){
				$this->ajaxReturn(200, '添加成功', '', 'closeCurrent');
			}else{
				$this->ajaxReturn(300, '添加失败');
			}
		}else{
			$this->assign('roles', $this->roles);
			$this->assign('status', $this->status);
			$this->display('Admin/View/Manager/add.php');
		}
	}
	
	/**
	 * 修改用户
	 */
	public function update(){
		if(count($_POST) > 0){
			$this->checkValidate('update');
			if($this->manager_model->where('uid='.$_POST['uid'])->update($_POST)){
				$this->ajaxReturn(200, '修改成功', '', 'closeCurrent');
			}else{
				$this->ajaxReturn(300, '修改失败');
			}
		}else{
			$uid = (int)$_GET['uid'];
			$user_info = $this->manager_model->where("uid=$uid")->select();
			$this->assign('user_info', $user_info[0]);
			$this->assign('roles', $this->roles);
			$this->assign('status', $this->status);
			$this->display('Admin/View/Manager/update.php');
		}
	}
	
	/**
	 * 删除用户
	 */
	public function delete(){
		$ids = $_GET['ids'];
		if(!empty($ids) && $this->manager_model->where("uid IN($ids)")->delete()){
			$this->ajaxReturn(200, '删除成功');
		}else{
			$this->ajaxReturn(300, '删除失败');
		}
	}
	
}
?>